package com.ding.commander;

import com.ding.common.*;

import java.net.Socket;
import java.util.logging.Logger;

import static com.ding.common.Constant.RECYCLE_PASSIVITY;
import static com.ding.common.Constant.RECYCLE_SUCCESS;


/*
    指令通道
 */
public class CommanderChannel extends MessageChannel {

    private Logger logger = Logger.getLogger("");

    private CommanderChannelHolder commanderChannelHolder;

    public void setCommanderChannelHolder(CommanderChannelHolder commanderChannelHolder) {
        this.commanderChannelHolder = commanderChannelHolder;
    }

    public CommanderChannel(Socket socket) {
        super(socket);
        setAfterCloseStrategy(() -> {
            if (this.commanderChannelHolder != null) {//在关闭的时候移除绑定关系
                this.commanderChannelHolder.removeCommander();
                logger.info("移除绑定关系");
            }

            this.getPool().closeAndRemoveByIntroducerId(getId());
            logger.info("已关闭由本通道引荐的通道");
        });
    }

    private Heartbeat heartbeat;

    //开始工作
    public void start(int c, int to) {
        sendMsg(new Message().type(Constant.HEARTBEAT).heartbeatInterval(c));
        heartbeat = new Heartbeat(c, to) {
            @Override
            protected void hearbeat() {
                if (isDeath()) {
                    clear();
                    System.out.println("超时死亡后关闭");
                    close();
                }
            }
        };
        heartbeat.start();

        Threads.exe(()->{
            while (true) {
                Message message = readMsg();
                if (message == null) {
                    break;
                }
                handleMsg(message);
            }
        });

    }


    private void handleMsg(Message message) {
        switch (message.getType()) {
            case RECYCLE_PASSIVITY://被动回收节点
                ((CPool) getPool()).recyclePassivity(message.getId());
                break;
            case RECYCLE_SUCCESS://回收成功
                ((CPool) getPool()).recycleSuccess(message.getId());
                break;
            case Constant.HEARTBEAT://心跳
                heartbeat.updateTime();
                break;
        }
    }


    public void sendNewStreamChannel(int size) {
        System.out.println("size=" + size);
        for (int i = 0; i < size; i++) {
            System.out.println("发送新建通信的指令--------------------");
            try {
                sendMsg(new Message().type(Constant.NEW_STREAM).introducerId(getId()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("发送新建通信的指令--------------------");
        }
    }

}
